package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.example.authforcmcc.AuthForCmcc;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.adapter.TestTaskListAdapter;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.GetAPInfo;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class TaskTestWlan2Widget extends GeneralTestWidget {
	public final static String PREFS_NAME = "mymobile";
    public final static String PREFS_KEY = "number";
	
    private Thread thread;
	public static Activity ctx;
	private static String TAG = "TaskWidget";
	private ListView taskListView;
	private List<Task> tasks = null;
	private TelManager tm;
	private Handler handler;
	private String myPhoneNumber;
	private List<Map<String, Object>> datas;
	private TestTaskListAdapter tAdapter = null;
	private ImageView image1 = null, image2 = null;
	private ProgressBar pb1 = null, pb2 = null;
	private Button begin_test = null;
	private TextView tv_progress1 = null, tv_progress2 = null;
	private LinearLayout linearlayout = null; 
	private int testNum;
	private Button resultButton;
	private TextView titleView;
	private Task task; 
    private WlanManager wlanManager;
	private boolean connected = false;
	private boolean connected2 = false;
	private boolean btnClick = false;
	private boolean isWebAuthsucceed = false;
	public boolean connecting = true;
	private boolean isPeap = false;
	public boolean isTesting = true;
	
	public TaskTestWlan2Widget(Activity context) {
		super(context);
		this.ctx = context;
		GlobalApp.taskTestWlan2Widget = this;
		inflate(context, R.layout.task_test_widget_wlan, this);
		GlobalApp.nowNetType = 1;
		GlobalApp.clearAll();
		GlobalApp.isPeapTested = false;
		
		wlanManager = new WlanManager(ctx);
		//task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);//获取任务
		task = GlobalApp.taskWlan;
		
		if(task == null) {
			System.out.println("task传值失败" );
		}else {
			System.out.println("网络类型：" + task.selNetType);//  +task.scanResult.BSSID
		}
		linearlayout = (LinearLayout)this.findViewById(R.id.progress_linearlayout_wlan);
		image1 = new ImageView(ctx);
		image1.setBackgroundResource(R.drawable.test_before);
		image2 = new ImageView(ctx);
		image2.setBackgroundResource(R.drawable.test_after);
		linearlayout.addView(image1, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		pb2 = (ProgressBar)findViewById(R.id.progress2_wlan);
		tv_progress1 = (TextView)findViewById(R.id.tv_progress1_wlan);
		tv_progress2 = (TextView)findViewById(R.id.tv_progress2_wlan);
		titleView = (TextView)findViewById(R.id.task_test_title_wlan);
		if(task.taskType == null) {
			titleView.setText("Wlan网络测试");
		} else {
			if(task.taskType.trim().equals("巡检测试")) {
				titleView.setText("Wlan巡检测试");
			} else if(task.taskType.trim().equals("验收测试")) {
				titleView.setText("Wlan验收测试");
			} else {
				titleView.setText("Wlan网络测试");
			}
		}
		/*String from = ctx.getIntent().getStringExtra("from");
    	from = from == null?"":from;
    	if(from.equals("TestWidget")) {
    		titleView.setText(R.string.test_task_title);
    	}else {
    		titleView.setText(task.taskType);
		}*/ 
//    	titleView.setText("Wlan网络测试");
		begin_test = (Button)findViewById(R.id.begin_tesk_wlan);
		begin_test.setText("测试中...");
		begin_test.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (btnClick) {
					ctx.setContentView(new TaskResult(ctx));
					btnClick = false;
				} 
			}
		});
		taskListView = (ListView) this.findViewById(R.id.taskTestListView_wlan);
		taskListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Map<String, Object> r = (Map<String, Object>) taskListView
						.getAdapter().getItem(position);
				
				Log.d("结果查看", "详细信息: " + r.toString());
			}
		});
		
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					init();
					dismissMessageDialog();
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				case MessageWhat.WIFI_SUCESS_CONNECTED:  
					if(isPeap) {
						dismissMessageDialog();
						//获取city、town
	                    new GetAPInfo(task.mac).start();
	                    if(GlobalApp.CITY == null || GlobalApp.CITY.length() < 2) {
	                    	new GetAPInfo(tm.getPhoneNumber(), false).start3();
	                    }
	                    connecting = false;
						start();
					} else {
						task.acIp = wlanManager.getIpAddress();
						ctx.getIntent().putExtra(TAG_REFER_TASK, task); 
						connecting = false;
						webAuth();
					}
                    break;
				case MessageWhat.LOGIN_SUCCESS:  
				case MessageWhat.LOGIN_FAILED: 
					dismissMessageDialog();
					//获取city、town
                    new GetAPInfo(task.mac).start();
                    if(GlobalApp.CITY == null || GlobalApp.CITY.length() < 2) {
                    	new GetAPInfo(tm.getPhoneNumber(), false).start3();
                    }
					start();
					break;
				}
			}
		};

        wlanManager.setHandler(handler);
		tm = new TelManager(ctx);
		tm.setHandler(handler); 
		if(task!=null && task.scanResult!=null){
			DBManager db = new DBManager(ctx);
			if(task.scanResult.SSID.equals(WlanManager.SSID_CMCC)) {
			//if(task.scanResult.SSID.equalsIgnoreCase("tp-link_5908cc")) {
				Account Account = db.getAccount();
				if((Account == null ||Account.userName == null || Account.password == null)
						|| (Account.userName.equals("") || Account.password.equals(""))){
					inputUserPassDialog();
				} else {
					connectNetWork();
				}
			} else if(task.scanResult.SSID.equals(WlanManager.SSID_CMCC_AUTO)) {
				isPeap = true;
				Account Account = db.getAccount();
				if((Account == null ||Account.userName == null || Account.password == null)
						|| (Account.userName.equals("") || Account.password.equals(""))){
					inputUserPassDialog();
				} else {
					//peap认证
					startPeap(task.scanResult);
				}
			} else{
				connectNetWork();
			}
			db.release();
		} else {
		    connectNetWork();
		}
	}
	
	
	 private void connectNetWork(){

		   showMessageDialog(ctx, "正在连接网络..."); 
		   
		   thread = new Thread() { 
		        @Override
		        public void run() {
		        	wlanManager.setMobileDataEnabled(false);
               	 	wlanManager.openWifi();
	                wlanManager.connect(task.scanResult);
		                
		        }  
		    };
	    	thread.start();
		   
	    }
	 private final class ApTestThreadPeap extends Thread {
	        private ScanResult scan;
	        public ApTestThreadPeap(final ScanResult scan) {
	            this.scan = scan;
	        }
	        @Override
	        public void run() {
	        	executable = true;
             connecting = true;
             wlanManager.setMobileDataEnabled(false);
        	 	wlanManager.openWifi();
             wlanManager.connect(scan);
             startConnectTimeoutListenerPeap();
	        }
	    }

	    private void startPeap(final ScanResult scan) {
	            final ApTestThreadPeap apTestThreadPeap = new ApTestThreadPeap(scan);
	            showMessageDialog(ctx, "正在连接网络...");
	            apTestThreadPeap.start();
	    }

	    private void startConnectTimeoutListenerPeap() {
	        TimerTask wifiReceiverTask = new TimerTask() {
	            public void run() {
	                if (connecting) {
	                    Log.e(TAG, "Peap认证测试连接超时");
	                    wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
	                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
	                }
	            }
	        };
	        Timer timer = new Timer();
	        timer.schedule(wifiReceiverTask, WlanManager.CONNECT_TIMEOUT);
	    }
	 
	 /**
	     * 配置认证账号和无线密码
	     * @param ctx
	     * @param wlanManager
	     * @param handler
	     */
	    private void inputUserPassDialog() {
	    	LayoutInflater factory = LayoutInflater.from(ctx);
			final View dialogView = factory.inflate(R.layout.web_input_user_pass_dialog, null);
			final EditText identText = (EditText) dialogView.findViewById(R.id.webusername); 
			final EditText passText = (EditText) dialogView.findViewById(R.id.webpassword); 
	        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
	        builder.setTitle("WEB认证账号"); 
	        builder.setView(dialogView); 
	        builder.setCancelable(false); 
	        builder.setPositiveButton("认证", new DialogInterface.OnClickListener() {
	         	public void onClick(DialogInterface dialog, int id) {
		       		 String username = identText.getText().toString(); 
		    		 String password = passText.getText().toString();
		    		 try { 
		    			 Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
						 field.setAccessible(true);
		    			 if (StringUtils.isEmpty(username)) {
							field.set(dialog, false);
							showMessage(ctx, "请输入认证账号");
						 }else if (StringUtils.isEmpty(password)) {
							field.set(dialog, false);
			    			showMessage(ctx, "请输入无线密码");
						 }else{ 
							 field.set(dialog, true);  
							 DBManager db = new DBManager(ctx);
							 Account config = new Account();
							 config.userName = username;
							 config.password = password;
							 db.saveAccount(config);
						 	 db.release();
						 }
		    		 } catch (Exception e) {
							e.printStackTrace();
							showMessage(ctx, "配置失败，请稍后重试");
					 }
		    		 if(isPeap) {
			    			//peap认证
							startPeap(task.scanResult);
			    		 } else {
			    			 connectNetWork();
			    		 }
			    		 dialog.dismiss();
	        	}
	        });
	        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
	        	public void onClick(DialogInterface dialog, int id) {
	        		try {
						Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(dialog, true);
					} catch (Exception e) {
						e.printStackTrace();
					}
	        		dialog.cancel();
	    			connectNetWork();
	        	}
	        });
		 	wifiListDialog = builder.create();
		    wifiListDialog.show(); 
	 
	    }

	    Handler handlerChildMessage = new Handler() {

			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message messag) {
				if(isTesting) {
					Message msg = updateHandler.obtainMessage();
					Message message = new Message();
					Object tempObject;
					Map<String, Object> t2;
					if(datas!=null && datas.size()>0){
						switch(messag.arg1) {
						case MessageWhat.HANDLER_START:
							testNum = 0;
							System.out.println("= = = =  收到消息0   = = = =");
							msg.arg1 = testNum; 
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
								new HttpTestWidgetProxy(ctx, handlerChildMessage);
							} else {
								message.arg1 = MessageWhat.HANDLER_HTTP;
								GlobalApp.result_HTTP_test=new StringBuffer("\n\nHTTP测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_HTTP:
							System.out.println("= = = =  收到消息1   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject = taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) { 
								new PingWidgetProxy(ctx, handlerChildMessage);
							} else   {
								message.arg1 = MessageWhat.HANDLER_PING;
								GlobalApp.result_PING_test=new StringBuffer("\n\nPING测试项已跳过");
							}   
							break;
							
						case MessageWhat.HANDLER_PING:
							System.out.println("= = = =  收到消息2   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
								new FtpTestProxyWidget(ctx, handlerChildMessage, tAdapter);
							} else {
								message.arg1 = MessageWhat.HANDLER_FTP;
								GlobalApp.result_FTP_test=new StringBuffer("\n\nFTP测试项已跳过");
							}
							break;
 						case MessageWhat.HANDLER_FTP:
							System.out.println("= = = =  收到消息4   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")
									&&task.scanResult!=null && task.scanResult.SSID!=null 
									&&task.scanResult.SSID.equals(WlanManager.SSID_CMCC)) {
								new WebauthTestWidgetProxy(ctx, handlerChildMessage);
							} else  {
								message.arg1 = MessageWhat.HANDLER_WEB;
								GlobalApp.result_WEB_test=new StringBuffer("\n\nWeb认证测试条件不满足");
							}
							break;
						case MessageWhat.HANDLER_WEB:
							System.out.println("= = = =  收到消息5   = = = ="); 
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) {
								new RssiTestWidgetProxy(ctx, handlerChildMessage);
							} else {
								message.arg1 = MessageWhat.HANDLER_RSSI;
								GlobalApp.result_SRRI_test =new StringBuffer("\n\n信号强度测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_RSSI:
							System.out.println("= = = =  收到消息3   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
								new ApRelevanceTestWidgetProxy(ctx, handlerChildMessage);
							} else {
								message.arg1 = MessageWhat.HANDLER_APREL;
								GlobalApp.result_AP_test=new StringBuffer("\n\nAP关联测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_APREL:
							System.out.println("= = = =  收到消息6   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							isTesting = false;
//							btnClick = true;
//							begin_test.setText("查看结果");
							break;
						case MessageWhat.HANDLER_SNR:
							break;
						}
					}
					handlerChildMessage.sendMessage(message);
				}
			}
		};

	Thread updateThread = new Thread() {

		@Override
		public void run() {
			// TODO Auto-generated method stub 
			pb2.setMax(datas.size());
		}
		
	};
	Handler updateHandler = new Handler() {
		private String testingName = "";
		public void handleMessage(Message msg) {
			if(msg.arg1 == -1) {
				ProgressBar pb = new ProgressBar(ctx);
				pb.setVisibility(VISIBLE);
				linearlayout.removeAllViews();
				linearlayout.addView(pb, new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1+1);
				testingName = t == null ?"":(String)t.get("taskName");
				if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("0")) {
					t.put("taskState", "3");
				} else if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("1")) {
					System.out.println(testingName + " 已跳过");
				}
				
			} else if(msg.arg1 < datas.size()-1){
				@SuppressWarnings("unchecked")
				Map<String, Object> t1 = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1);
				@SuppressWarnings("unchecked")
				Map<String, Object> t2 = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1+1);
				testingName = t2==null?"":(String)t2.get("taskName");
				if(t1!=null && t1.get("taskSkip")!=null &&t1.get("taskSkip").equals("0")) {
					t1.put("taskState", "1");
				} else if(t1!=null && t1.get("taskSkip")!=null &&t1.get("taskSkip").equals("1")) {
					System.out.println(t1.get("taskName") + " 已跳过");
				}
				if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) {
					t2.put("taskState", "3");
				} else if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("1")) {
					System.out.println(t2.get("taskName") + " 已跳过");
				}
			} else if(msg.arg1 == datas.size()-1) {
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1);
				if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("0")) {
					t.put("taskState", "1");
				} else if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("1")) {
					System.out.println(t.get("taskName") + " 已跳过");
				}
			}
			
			if(msg.arg1+1 >= datas.size()) {
				tv_progress2.setText("检测完毕");
				btnClick = true;
				begin_test.setText("查看结果");
				linearlayout.removeAllViews();
				linearlayout.addView(image2, new LayoutParams(
						LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 

				//=============================自动跳转到测试结果页面上传结果
				if (btnClick) {
					
					task.endsTime = StringUtils.getDateTime();

					if (tm.getNetworkType()!=null && ( tm.getNetworkType().equals("HSDPA") || tm.getNetworkType().equals("HSUPA") )) {
						GlobalApp.TDorGSM_task = WlanManager.TD;
						ctx.setContentView(new TaskTestTDWidget(ctx)); //直接跳转到TD网络测试
						
					} else {
						
						GlobalApp.TDorGSM_task = WlanManager.GSM;
						ctx.setContentView(new TaskTestGSMWidget(ctx)); //直接跳转到GSM网络测试
					}
					
					btnClick = false;
				}
				ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		    	//================================================================
				
			} else {
				tv_progress2.setText("正在检测第" + (msg.arg1+2) + "项：" + testingName);
			}
			
			tv_progress1.setText("总进度：" + 100*(msg.arg1+1)/datas.size() + "%");
			pb2.setProgress(msg.arg1+1);
			tAdapter.notifyDataSetChanged();  //更新Adapter
		}
	}; 
	
	public void webAuth(){
		isWebAuthsucceed = false;

		if (task.scanResult != null
				&& task.scanResult.SSID.equals(WlanManager.SSID_CMCC)) {
			WebAuthManager wManager = new WebAuthManager(ctx);
			String defaultUrl = ctx.getResources().getString(
					R.string.default_url);
			DBManager db = new DBManager(ctx);
			Account config = db.getAccount();
			String userName = "", pwd = "";
			if (null != config) {
				userName = config.userName;
				pwd = config.password;
				// isWebAuthsucceed = wManager.auth(defaultUrl, userName, pwd);
				AuthForCmcc authForCmcc = new AuthForCmcc(ctx, handler,
						userName, pwd);
				authForCmcc.startAuth();
			} else {
				showMessage(ctx, "WEB认证错误，请检查账号配置.");
			}
			db.release();
		} else if (GlobalApp.DEBUG) {
			AuthForCmcc authForCmcc = new AuthForCmcc(ctx, handler, "", "");
			authForCmcc.startAuth();
		}
		// if(isWebAuthsucceed) {
		// wlanManager.sendMsg(MessageWhat.LOGIN_SUCCESS);
		// } else {
		// wlanManager.sendMsg(MessageWhat.LOGIN_FAILED);
		// }

	}
	
	public void start() { 
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		 myPhoneNumber = tm.getPhoneNumber();
		if (StringUtils.isEmpty(myPhoneNumber)) {
			showMessage(ctx, "获取本机号码失败,请输入.");
			showInputDialog();
			return;
		} else {
			loadTaskList();
		}
	}

	private void showInputDialog() {
		LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(
				R.layout.input_phone_num_dialog, null);
		final EditText inputText = (EditText) dialogView
				.findViewById(R.id.phoneNumEditText);
		AlertDialog.Builder inputBuilder = new AlertDialog.Builder(ctx);
		inputBuilder.setTitle("提示");
	//	inputBuilder.setIcon(R.drawable.smile);
		inputBuilder.setView(dialogView);
		inputBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (StringUtils.isEmpty(inputText.getText().toString())) {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							showMessage(ctx, "请输入本机号码");
						} else {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
							myPhoneNumber = inputText.getText().toString();
							SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME,0);
				            SharedPreferences.Editor editor = settings.edit();
				            editor.putString(PREFS_KEY, myPhoneNumber);
				            editor.commit();   //保存手机号码
				            
							dialog.cancel();
							loadTaskList();
						}
					}
				});
		inputBuilder.setNegativeButton("取消", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					Field field = dialog.getClass().getSuperclass()
							.getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				dialog.cancel();
			}
		});
		Dialog dialog = inputBuilder.create();
		dialog.show();
	}

	private void loadTaskList() {
		//this.showMessageDialog(ctx, "正在加载任务列表...");
		new Thread() {
			public void run() {
				getTasks();
			}
		}.start();
	}

	private void init() { 
		tAdapter = new TestTaskListAdapter(ctx, datas);
		taskListView.setAdapter(tAdapter);
		task.startTime = StringUtils.getDateTime();
		task.startsTime = StringUtils.getDateTime();
		testNum = 0; 
		pb2.setMax(datas.size());
		Message msg = new Message();
		msg.arg1 = -1;
		updateHandler.sendMessage(msg);

		Message message = handlerChildMessage.obtainMessage();
		message.arg1 = MessageWhat.HANDLER_START;
		message.sendToTarget();
	}
	
	private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();

		try {
			tasks = new ArrayList<Task>();
			Task tk0 = new Task();  Task tk1 = new Task();
			Task tk2 = new Task();  Task tk3 = new Task();
			Task tk4 = new Task();  Task tk = new Task();
			tk0.taskName = "HTTP测试";  tk1.taskName = "FTP测试";
			tk2.taskName = "PING测试";  tk3.taskName = "AP关联";
			tk4.taskName = "WEB认证";  tk.taskName = "信号强度RSSI"; 

				tasks.add(tk0); 
				tasks.add(tk2); 
				tasks.add(tk1);
				tasks.add(tk4); 
				tasks.add(tk3);
				tasks.add(tk);

			Map<String, Object> t = null;
			for (Task task : tasks) {
				t = new HashMap<String, Object>();
				t.put("taskName", task.taskName);
				t.put("taskState", "0");  //检测状态
				t.put("taskSkip", "0");   //是否跳过
				
				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);

		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		}
		return res;
	}

}
